package com.whq.security.security;

import io.jsonwebtoken.CompressionCodecs;
import io.jsonwebtoken.Jwts;
import io.jsonwebtoken.SignatureAlgorithm;
import org.springframework.stereotype.Component;

import java.util.Date;

@Component
public class TokenManager {

    //token有效时长
    private long tokenExpiration = 24 * 60 * 60;
    //秘钥
    private String tokenSignKey = "123456";

    public String createToken(String username) {
        String token = Jwts.builder().setSubject(username).setExpiration(new Date(System.currentTimeMillis() + tokenExpiration))
                .signWith(SignatureAlgorithm.HS512, tokenSignKey).compressWith(CompressionCodecs.GZIP).compact();
        return token;
    }

    public String getUserInfoFromToken(String token){
        String subject = Jwts.parser().setSigningKey(tokenSignKey).parseClaimsJws(token).getBody().getSubject();
        return subject;
    }

    public void removeToken(String token){

    }

    public static void main(String[] args) {
        TokenManager manager = new TokenManager();
        String token = manager.createToken("wuhaiqiang");
        String userInfo = manager.getUserInfoFromToken(token);
        System.out.printf("%s\n",token);
        System.out.printf("%s\n",userInfo);
    }
}
